package vip.xiaonuo.biz.modular.qhhistory.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Slf4j
@UtilityClass
public class ExcelListenerUtil {
    public static String DATASOURCE = null;

    /**
     * 创建监听器
     *
     * @param consumer  消费者
     * @param threshold 批量写入数
     * @param <T>
     * @return
     */

    public <T> AnalysisEventListener<T> getListener(Consumer<List<T>> consumer, int threshold) {
        return new AnalysisEventListener<>() {
            private final List<T> dataList = new LinkedList<>();

            @Override
            public void invoke(T t, AnalysisContext analysisContext) {
                //解析行
                dataList.add(t);
                if (dataList.size() == threshold) {
                    consumer.accept(dataList);
                    dataList.clear();
                }
            }

            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                //解析头
                log.info("表格头信息：【{}】", headMap);
                //获取表格头数据
                if (StrUtil.isBlank(DATASOURCE)) {
                    //将表格标题放入缓存，自行定义缓存
                    DATASOURCE = headMap.get(0);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //结束解析
                if (dataList.size() > 0) {
                    consumer.accept(dataList);
                }
                //清空内存的缓存数据
                ExcelListenerUtil.DATASOURCE = null;
            }
        };
    }
}
